package com.huang.springbootthymeleafshiro.shiro.realm;


import com.huang.springbootthymeleafshiro.bean.Pers;
import com.huang.springbootthymeleafshiro.bean.Role;
import com.huang.springbootthymeleafshiro.bean.User;
import com.huang.springbootthymeleafshiro.service.UserService;
import com.huang.springbootthymeleafshiro.shiro.redis.MyByteSource;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.List;

public class CustomerRealm extends AuthorizingRealm {
    @Autowired
    private UserService service;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取当前主身份信息
        String principal = (String) principalCollection.getPrimaryPrincipal();

        //根据身份  获取权限
        User user = service.findRolebyname(principal);
        //获取用户角色
        List<Role> roles = user.getRoles();
        if(!StringUtils.isEmpty(roles)){
            SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
            for (Role role : roles) {
                //将角色赋予
                authorizationInfo.addRole(role.getName());
                //将权限赋予
                List<Pers> persList = service.findPersbyid(role.getId());
                if(StringUtils.isEmpty(persList)){
                    for (Pers pers : persList) {
                        authorizationInfo.addStringPermission(pers.getName());
                    }

                }

            }
            return authorizationInfo;
        }


        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String principal = (String) authenticationToken.getPrincipal();
        User user = service.findbyname(principal);

        if(user!=null){
            return  new SimpleAuthenticationInfo(principal,user.getPwd(), new MyByteSource(user.getSalt()),this.getName());
        }
        return null;
    }
}
